package com.jiutong.meipengdai.ui.fragments;

import android.animation.ValueAnimator;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.jiutong.meipengdai.R;
import com.jiutong.meipengdai.base.BaseFragment;
import com.jiutong.meipengdai.common.Constants;
import com.jiutong.meipengdai.entity.AccountInfoRespond;
import com.jiutong.meipengdai.entity.BaseRespond;
import com.jiutong.meipengdai.http.model.requests.MyAccountRequest;
import com.jiutong.meipengdai.http.present.CommonPresent;
import com.jiutong.meipengdai.http.subscribers.ProgressSubscriber;
import com.jiutong.meipengdai.http.subscribers.SubscriberOnNextListener;
import com.jiutong.meipengdai.ui.activitys.AboutUsActivity;
import com.jiutong.meipengdai.ui.activitys.AccountSettingActivity;
import com.jiutong.meipengdai.ui.activitys.AllLoanActivity;
import com.jiutong.meipengdai.ui.activitys.BankCardListActivity;
import com.jiutong.meipengdai.ui.activitys.EvaluateRecordActivity;
import com.jiutong.meipengdai.ui.activitys.GatheringActivity;
import com.jiutong.meipengdai.ui.activitys.HouseListActivity;
import com.jiutong.meipengdai.ui.activitys.LoanApplyActivity;
import com.jiutong.meipengdai.ui.activitys.MsgCenterActivity;
import com.jiutong.meipengdai.ui.activitys.UserInfoAcitivity;
import com.jiutong.meipengdai.utils.NumUilt;
import com.jiutong.meipengdai.utils.SpConfig;
import com.jiutong.meipengdai.utils.ToastUtil;
import com.jiutong.meipengdai.views.CircleProgressView;
import com.jiutong.meipengdai.views.GlideCircleTransform;
import com.jiutong.meipengdai.views.dialog.ChangeUrlDialog;
import com.orhanobut.logger.Logger;

import java.util.HashMap;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by suxi on 2017/6/19.
 */

public class PersonalCenterFragment extends BaseFragment {
    @Bind(R.id.iv_heade)
    ImageView ivHeade;
    @Bind(R.id.tv_user_name)
    TextView tvUserName;
    @Bind(R.id.tv_msg_count)
    TextView tvMsgCount; //消息
    @Bind(R.id.tv_evaluate_record)
    TextView tvEvaluateRecord;
    @Bind(R.id.tv_my_housess)
    TextView tvMyHousess;
    @Bind(R.id.tv_my_shoukuan)
    TextView tvMyShoukuan;
    @Bind(R.id.tv_bank_card)
    TextView tvBankCard;
    @Bind(R.id.tv_my_core)
    TextView tvMyCore; //我的积分
    @Bind(R.id.tv_loan)
    TextView tvLoan;//我的贷款
    @Bind(R.id.rl_my_loan)
    RelativeLayout rlMyLoan;
    @Bind(R.id.tv_shoud_pay)
    TextView tvShoudPay;
    @Bind(R.id.tv_huankuan)
    TextView tvHuankuan; //还款
    @Bind(R.id.tv_apply_time)
    TextView tvApplyTime; //还款时间
    @Bind(R.id.ll_repayment)
    LinearLayout llRepayment;
    @Bind(R.id.rl_account_setting)
    RelativeLayout rlAccountSetting;
    @Bind(R.id.rl_about_us)
    RelativeLayout rlAboutUs;
    @Bind(R.id.rl_msg)
    RelativeLayout rlMsg;
    @Bind(R.id.tv_yidai)
    TextView tvYidai;
    @Bind(R.id.tv_kedai)
    TextView tvKedai;
    @Bind(R.id.iv_msg)
    ImageView ivMsg;
    @Bind(R.id.tv_no_huankuan)
    TextView tvNoHuankuan;
    @Bind(R.id.tv_total_amount)
    TextView tvTotalAmount;
    @Bind(R.id.tv_apply_time_desc)
    TextView tv_apply_time_desc;
    @Bind(R.id.ll_apply_time)
    LinearLayout llApplyTime;
    @Bind(R.id.cpv_view)
    CircleProgressView cpv_view;
    @Bind(R.id.sv_container)
    ScrollView svContainer;
    private boolean mHidden;
    private MyAccountRequest mapRequest;
    private SubscriberOnNextListener onNextListener;
    private HashMap<String, Object> fieldsMap;
    private ProgressSubscriber progressSubscriber;
    private ChangeUrlDialog changeUrlDialog;

    @Override
    protected int getLayoutResouceId() {
        return R.layout.fragment_personal_center;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        ButterKnife.bind(this, rootView);
//        rlAboutUs.setOnLongClickListener(new View.OnLongClickListener() {
//            @Override
//            public boolean onLongClick(View v) {
//
//                showChangeUrlDialog();
//                return false;
//            }
//        });
        return rootView;
    }

    private void showChangeUrlDialog() {
        if (changeUrlDialog == null)
            changeUrlDialog = new ChangeUrlDialog();

        changeUrlDialog.show(getFragmentManager(), TAG);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @OnClick({R.id.iv_heade, R.id.tv_evaluate_record, R.id.tv_my_housess, R.id.tv_my_shoukuan, R.id.tv_kedai,
            R.id.tv_bank_card, R.id.rl_my_loan, R.id.rl_msg, R.id.tv_user_name,
            R.id.rl_account_setting, R.id.rl_about_us})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_heade: //头像
            case R.id.tv_user_name:
                openActivity(UserInfoAcitivity.class);
                break;
            case R.id.rl_msg: //消息
                openActivity(MsgCenterActivity.class);
                break;
            case R.id.tv_evaluate_record: //我的评估
                openActivity(EvaluateRecordActivity.class);
                break;
            case R.id.tv_my_housess: //我的房产
                openActivity(HouseListActivity.class);
                break;
            case R.id.tv_my_shoukuan:// 我的收款
                openActivity(GatheringActivity.class);
                break;
            case R.id.tv_bank_card: //我的银行卡
                openActivity(BankCardListActivity.class);
                break;
            case R.id.rl_my_loan://我的贷款
                openActivity(AllLoanActivity.class);
                break;
            case R.id.rl_account_setting: //账户设置
                openActivity(AccountSettingActivity.class);
//                ToastUtil.shortToast(getActivity(), "补丁更新成功");
                break;
            case R.id.rl_about_us: //关于我们
                openActivity(AboutUsActivity.class);

                break;
            case R.id.tv_kedai: //可贷额度
                openActivity(LoanApplyActivity.class);
                break;
        }
    }

    @Override
    public void onResume() {
        super.onResume();

        if (mHidden)
            return;
        //只会执行一次？？？
        doNetWork();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        mHidden = hidden;
        if (!hidden) {

            doNetWork();
        }
    }

    private void doNetWork() {

        if (svContainer != null)
            svContainer.scrollTo(0, 0);

        if (!TextUtils.isEmpty(SpConfig.getInstance().getString(Constants.SESSIONID_STRING))) {

            if (!TextUtils.isEmpty(SpConfig.getInstance().getString(Constants.TEPPHONE_STRING))) {
                tvUserName.setText(SpConfig.getInstance().getString(Constants.TEPPHONE_STRING));
            }

            if (!TextUtils.isEmpty(SpConfig.getInstance().getString(Constants.REALNAME_STRING))) {
                tvUserName.setText(SpConfig.getInstance().getString(Constants.REALNAME_STRING));
            }

            getAccountInfo();

        } else {

            ivHeade.setImageResource(R.mipmap.gray_head_icon);
            tvNoHuankuan.setVisibility(View.VISIBLE);
            llApplyTime.setVisibility(View.GONE);
            tvHuankuan.setVisibility(View.GONE);
            cpv_view.setProgress(0);

            tvUserName.setText("登录/注册");
            tvYidai.setText("已贷总额度(元):0.00");
            tvKedai.setText("0.00");
            tvTotalAmount.setText("0.00");
        }
    }

    /**
     * 获取账户信息
     */
    public void getAccountInfo() {

        if (mapRequest == null) {
            mapRequest = new MyAccountRequest();
        }

        onNextListener = new SubscriberOnNextListener<AccountInfoRespond>() {
            @Override
            public void onNext(AccountInfoRespond subjects) {

                if ("200".equals(subjects.getResCode())) {

                    if (!TextUtils.isEmpty(SpConfig.getInstance().getString(Constants.REALNAME_STRING))) {
                        tvUserName.setText(SpConfig.getInstance().getString(Constants.REALNAME_STRING));
                    }

                    //已贷额度
                    String loanAmount = NumUilt.formatDouble(subjects.getData().getLoanAmount());
                    //可贷额度
                    String amountSum = NumUilt.formatDouble(subjects.getData().getAmountSum());

                    float loanAmountFloat = Float.parseFloat(loanAmount);
                    //地址以后会修改，目前拼接
                    Glide.with(mActivity).load("http://" + SpConfig.getInstance().getString(Constants.HEADERIMG_STRING)).transform(new CenterCrop(mActivity), new GlideCircleTransform(mActivity))
                            .diskCacheStrategy(DiskCacheStrategy.ALL)
                            .crossFade().into(ivHeade);


                    if (loanAmountFloat == 0) {
                        tvYidai.setText("已贷总额度(元):0.00");
                    } else {
                        tvYidai.setText("已贷总额度(元):" + (loanAmountFloat >= 10000 ? NumUilt.formatFloat(loanAmountFloat / 10000) + "万" : loanAmountFloat));
                    }

                    float amountFloat = Float.parseFloat(amountSum);
                    if (amountFloat == 0) {
                        tvKedai.setText("0.00");
                    } else {

                        if (amountFloat >= 10000) {
                            tvKedai.setText(NumUilt.formatFloat(amountFloat / 10000) + "万");
                        } else {
                            tvKedai.setText(NumUilt.formatFloat(amountFloat));
                        }
                    }
                    float totalAmount = loanAmountFloat + amountFloat;

                    tvTotalAmount.setText(totalAmount >= 10000 ? NumUilt.formatFloat(totalAmount / 10000) + "万" : NumUilt.doubleFormat(totalAmount + ""));

                    if (TextUtils.isEmpty(subjects.getData().getScore()) || Integer.parseInt(subjects.getData().getScore()) == 0) {
                        tvMyCore.setText("0 分");
                    } else {
                        tvMyCore.setText(subjects.getData().getScore() + "分");
                    }

                    cpv_view.setMax(360); //以300为最大，这样画进度条会平滑一些
                    ValueAnimator animator = ValueAnimator.ofFloat(0, loanAmountFloat / totalAmount * 360);
//                    ValueAnimator animator = ValueAnimator.ofFloat(0, 0.30f * 360);
                    animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                        @Override
                        public void onAnimationUpdate(ValueAnimator animation) {
                            float progress = (float) animation.getAnimatedValue();
                            cpv_view.setProgress((int) progress);
                        }
                    });

                    animator.setDuration(2000);
                    animator.start();

                    double currentSumAmount = subjects.getData().getCurrentSumAmount();

//                    if(subjects.getData().getHouseLoanPojoList() == null || subjects.getData().getHouseLoanPojoList().size() < 1)
//                    {
//                        tvNoHuankuan.setVisibility(View.VISIBLE);
//                        llApplyTime.setVisibility(View.GONE);
//                        tvHuankuan.setVisibility(View.GONE);
//                        return;
//                    }

//                    String currentAmount = subjects.getData().getHouseLoanPojoList().get(0).getCurrentAmount();
//                    double amountDouble = Double.parseDouble(currentAmount);
//                    double yinghuankuan = currentSumAmount - amountDouble;

                    double yinghuankuan = currentSumAmount;

                    if (yinghuankuan <= 0) {
                        tvNoHuankuan.setVisibility(View.VISIBLE);
                        llApplyTime.setVisibility(View.GONE);
                        tvHuankuan.setVisibility(View.GONE );
                    } else {
                        tvNoHuankuan.setVisibility(View.GONE);
                        llApplyTime.setVisibility(View.VISIBLE);
                        tvHuankuan.setVisibility(View.VISIBLE);
                        tvHuankuan.setText("¥ " + (int) yinghuankuan);

                        int parseInt = subjects.getData().getMonthRepaymentDays();
                        if (parseInt < 0) {
                            tv_apply_time_desc.setText("逾期");
                            tvApplyTime.setText(Math.abs(parseInt) + "");
                        } else {
                            tv_apply_time_desc.setText("距离下次还款还有");
                            tvApplyTime.setText(parseInt + "");
                        }
                    }

                } else {

                    ivHeade.setImageResource(R.mipmap.gray_head_icon);
                    tvNoHuankuan.setVisibility(View.VISIBLE);
                    llApplyTime.setVisibility(View.GONE);
                    tvHuankuan.setVisibility(View.GONE);
                    cpv_view.setProgress(0);

                    if (!TextUtils.isEmpty(SpConfig.getInstance().getString(Constants.REALNAME_STRING))) {
                        tvUserName.setText(SpConfig.getInstance().getString(Constants.REALNAME_STRING));
                    }

                    tvYidai.setText("已贷总额度(元):0.00");
                    tvKedai.setText("0.00");
                    tvTotalAmount.setText("0.00");

                }

            }

            @Override
            public void onError(Throwable e) {

            }
        };

        fieldsMap = new HashMap<>();
        progressSubscriber = new ProgressSubscriber(onNextListener, mActivity);

        mapRequest.getAccountInfo(progressSubscriber, fieldsMap);
    }
}
